import { useToast } from '@/hooks/use-toast';
import { adminUpdateShopStatus } from '@/service/actions/shop';
import { Label } from '@radix-ui/react-label';
import { useState, useTransition } from 'react';
import { Button } from '../ui/button';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from '../ui/dialog';
import { Textarea } from '../ui/textarea';

export default function WarningButton({
  shopId,
  button,
}: { shopId: number; button: React.ReactNode }) {
  const { toast } = useToast();
  const [open, setOpen] = useState(false);
  const [warningReason, setWarningReason] = useState('');
  const [isPending, startTransition] = useTransition();

  return (
    <Dialog open={open}>
      <DialogTrigger asChild onClick={() => setOpen(true)}>
        {button}
      </DialogTrigger>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>警告商铺</DialogTitle>
          <DialogDescription className="hidden" />
        </DialogHeader>
        <div>
          <Label>警告原因</Label>
          <Textarea
            rows={3}
            value={warningReason}
            onChange={(e) => setWarningReason(e.target.value)}
            className="resize-none"
          />
        </div>
        <div className="flex justify-end gap-2">
          <Button
            variant="outline"
            onClick={() => {
              setOpen(false);
              setWarningReason('');
            }}
          >
            取消
          </Button>
          <Button
            disabled={isPending}
            onClick={() => {
              if (!warningReason)
                return toast({
                  title: '请输入警告原因',
                  variant: 'destructive',
                });
              startTransition(async () => {
                const { error } = await adminUpdateShopStatus({
                  status: 'warning',
                  shopId,
                  warningReason,
                });
                error &&
                  toast({
                    title: error.message,
                    variant: 'destructive',
                  });
                if (!error) {
                  toast({ title: '已警告' });
                  setOpen(false);
                  setWarningReason('');
                }
              });
            }}
          >
            {isPending && <span className="i-ri-loader-4-line animate-spin" />}
            确定
          </Button>
        </div>
      </DialogContent>
    </Dialog>
  );
}
